package com.rsscollector.controller.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;

import org.springframework.context.i18n.LocaleContextHolder;

public class LocaleFilter implements Filter {

    private String language = "en";

	public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {
    	
    	String localeParam = request.getParameter("locale");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		Locale localeObj;
    	if (localeParam != null) {
    		// Update session's locale for JSTL and Struts
    		localeObj = new Locale(localeParam);
    		session.setAttribute(org.apache.struts.Globals.LOCALE_KEY, localeObj);
    		Config.set(session, Config.FMT_LOCALE, localeObj);
    	} else if (session.getAttribute(org.apache.struts.Globals.LOCALE_KEY) == null){
    		// if no locale has been set for this session, use default
    		String defaultLocale = this.language;
    		localeObj = new Locale(defaultLocale);
    		session.setAttribute(org.apache.struts.Globals.LOCALE_KEY, localeObj);    		
    		Config.set(session, Config.FMT_LOCALE, localeObj);
    	} else {
    		localeObj = (Locale) session.getAttribute(org.apache.struts.Globals.LOCALE_KEY);
    	}

    	// Set request locale for Spring
    	LocaleContextHolder.setLocale(localeObj);
    	
		// Pass control on to the next filter
		chain.doFilter(request, response);

    }

    public void init(FilterConfig filterConfig) throws ServletException {
    	String languageParam  = filterConfig.getInitParameter("language");
    	if (languageParam != null && !languageParam.trim().equals("")) {
    		this.language = languageParam.trim();
    	}
    }

    public void destroy() {
    }
}
